<?php

namespace Db;

use Application\Config as Cfg;
use \Exception as Exc;

import('Application.Config');
import('Db.Query');

class Connection {

    protected $handle;
    protected $dsn;
    protected $queryStr;

    protected function __construct(array $conSpec) {
        $this->dsn = "{$conSpec['dbms']}:host={$conSpec['host']};port={$conSpec['port']};dbname={$conSpec['database']}";
        try {
            $this->handle = new \PDO($this->dsn, $conSpec['user'], $conSpec['password']);
        } catch (Exc $e) {
            throw new Exc("Couldn't connect to the database. {$e->getMessage()}");
        }
        return $this;
    }

    public static function Open(array $conSpec = []) {

        if (empty($conSpec)) {
            $conSpec = [
                'dbms' => Cfg::DbConnDbms,
                'host' => Cfg::DbConnHost,
                'port' => Cfg::DbConnPort,
                'user' => Cfg::dbConnUser,
                'password' => Cfg::dbConnPassword,
                'database' => Cfg::DbConnDb,
            ];
        }

        return new Connection($conSpec);
    }

    public function Query(Query $query) {
        $this->queryStr = $query->Make();
        return $this->handle->query($this->queryStr)->fetchAll();
    }

    public function Prepare(Query $query, array $valuesArray = []) {
        $this->queryStr = $query->Make();
        $ret = $this->handle->prepare($this->queryStr);
        $ret->execute($valuesArray);
        return $ret->fetchAll();
    }
}